package com.cctc.demo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.cctc.demo.domain.Product;
import com.cctc.framework.dao.BaseDao;

@Repository
public class ProductDao<T extends Product> extends BaseDao<Object>
{
    private static final String PRODUCT_COUNT = "SELECT COUNT(*) FROM CCTC.CCTCT_PRODUCT";
    private static final String PRODUCT_LIST = "SELECT id, ATTR1, ITEMID, LISTPRICE, NAME, STATUS, UNITCOST FROM cctc.cctct_product LIMIT ?, ?";
    
    public List<Product> getAllProduct(int pageNumber, int pageSize)
    {
        // return getHibernateTemplate().find("From Product");
        return getJdbcTemplate().query(PRODUCT_LIST, new Object[] { pageNumber, pageSize },
                new int[] { Types.INTEGER, Types.INTEGER }, new ProductMapper());
    }
    
    public int getProductCount()
    {
        Number number = getJdbcTemplate().queryForObject(PRODUCT_COUNT, Integer.class);
        return (number != null ? number.intValue() : 0);
    }
    
    protected class ProductMapper implements RowMapper<Product>
    {
        public Product mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            Product product = new Product();
            product.setId(rs.getString("ID"));
            product.setAttr1(rs.getString("ATTR1"));
            product.setItemId(rs.getString("ITEMID"));
            product.setListPrice(rs.getDouble("LISTPRICE"));
            product.setName(rs.getString("NAME"));
            product.setStatus(rs.getString("STATUS"));
            product.setUnitCost(rs.getDouble("UNITCOST"));
            return product;
        }
    }
}
